package com.zkingsoft.web.interceptor;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.matrix.async.service.AsyncTaskService;
import com.zkingsoft.common.constance.AppConstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.matrix.core.tools.LogUtil;
import com.matrix.core.tools.StringUtils;
import com.matrix.core.tools.UUIDUtil;
import com.matrix.core.tools.WebUtil;
import com.zkingsoft.web.bean.VisitorLog;
import com.zkingsoft.web.dao.VisitorLogDao;
import com.zkingsoft.web.service.BusParameterSettingsService;
import com.zkingsoft.web.tool.Tools;

/**
 * 访问日志记录拦截器
 * 
 * @author JIANGYOUYAO
 * @email 935090232@qq.com
 * @date 2017年11月29日
 */
public class VisitorLogInterceptor implements HandlerInterceptor {

	@Resource(name = "busParameterSettingsService")
	private BusParameterSettingsService busParameterSettingsService;

	@Autowired
	private VisitorLogDao visitorLogDao;

	@Autowired
	private AsyncTaskService AsyncTaskService;

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
	}

	/**
	 * 通用拦截器
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {
		String visitorLogId=UUIDUtil.getRandomID();
		VisitorLog visitorLog = new VisitorLog();
		visitorLog.setId(visitorLogId);
		visitorLog.setCreateBy("system");
		visitorLog.setCreateTime(new Date());
		visitorLog.setUpdateBy("system");
		visitorLog.setUpdateTime(new Date());
		visitorLog.setCompanyId(Tools.getCompanyId());

		String host = WebUtil.getRequest().getServerName();
		visitorLog.setDomainName(host);
		// 获得请求的链接
		String url = WebUtil.getLocation();
		visitorLog.setUrl(url);
		
		// 获取请求的ip
		String ip = request.getHeader("X-Forwarded-For");
		if (ip == null) {
			String ip2 = request.getHeader("x-forwarded-for");
			LogUtil.info("#ip2---->{}#", ip2);
			ip = request.getRemoteAddr();
		}
		
		visitorLog.setIp(ip);
		
		
		String userAgent = request.getHeader("User-Agent");
		visitorLog.setVisitorEquipment(getEquipment(userAgent));
		visitorLog.setInfo2(userAgent);
		LogUtil.info("#请求者IP为:{},User-Agent为:{}#", ip, userAgent);
		Map<String, String> dataMap = new HashMap<>();
		dataMap.put("visitorLogId", visitorLogId);
		dataMap.put("ip", ip);
		AsyncTaskService.createTask(AppConstance.USER_TYPE_DEVELOPER, "设置访问地址", dataMap);
		visitorLogDao.insert(visitorLog);
		return true;
	}

	// 2.声明手机和平板的UA的正则表达式
	// \b 是单词边界(连着的两个(字母字符 与 非字母字符) 之间的逻辑上的间隔),
	// 字符串在编译时会被转码一次,所以是 "\\b"
	// \B 是单词内部逻辑间隔(连着的两个字母字符之间的逻辑上的间隔)
	String phoneReg = "\\b(ip(hone|od)|android|opera m(ob|in)i" + "|windows (phone|ce)|blackberry"
			+ "|s(ymbian|eries60|amsung)|p(laybook|alm|rofile/midp" + "|laystation portable)|nokia|fennec|htc[-_]"
			+ "|mobile|up.browser|[1-4][0-9]{2}x[1-4][0-9]{2})\\b";
	String tableReg = "\\b(ipad|tablet|(Nexus 7)|up.browser" + "|[1-4][0-9]{2}x[1-4][0-9]{2})\\b";
	// 3.移动设备正则匹配：手机端、平板
	Pattern phonePat = Pattern.compile(phoneReg, Pattern.CASE_INSENSITIVE);
	Pattern tablePat = Pattern.compile(tableReg, Pattern.CASE_INSENSITIVE);

	private Integer getEquipment(String userAgent) {
		// 1. 获得请求UA
		userAgent = userAgent.toLowerCase();
		if (null == userAgent) {
			userAgent = "";
		}
		// 4.匹配
		Matcher matcherPhone = phonePat.matcher(userAgent);
		Matcher matcherTable = tablePat.matcher(userAgent);
		if (matcherPhone.find()) {
			return 3; // 平板
		} else if (matcherTable.find()) {
			return 2; // 手机
		} else {
			return 1; // 来自PC
		}
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object arg2, Exception arg3)
			throws Exception {

	}

}
